<?php
require '../../../loader.php';
require 'common.php';
use bibi\Bibi;

$database = $_POST['database']??'';
$app = 'web';

if ($database ==''){
    error('数据库不能为空');
}

$db =  Bibi::db($database);

$appPath = ROOT.DS.APP.DS.$app;

if (!file_exists($appPath)){
    error('应用不存在');
}

try{
    $project = require($appPath.DS.'project.php');
}catch(\Exception $e){
    error($e->getMessage());
}

if ($project['status']){
    error('应用已安装');
}

$setupPath = $appPath.DS.'_setup';

$driver = $db->getConfig()['driver'];

try{
    foreach($project['model'] as $modelName => $model){
        $path = $setupPath.DS.'model'.DS.$modelName.DS.$driver.'.sql';
        
        if (!file_exists($path)){
            error('缺少数据库文件'.$modelName);
        }
    
        $sql = file_get_contents($path);
        $db->query($sql);
    
        $project['model'][$modelName]['config'] = $database;
    }
}catch(\Exception $e){
    error($e->getMessage());
}

$project['status']  =  true;

//重新写入

file_put_contents($appPath.DS.'project.php', '<?php return '.var_export($project,true).';');

//清空缓存
if (function_exists('opcache_reset')) opcache_reset();

$config = Bibi::config('system');

if (!$config->exists('default_app')){
    $config->default_app = $app;
    $config->save();
}

success('安装成功');